//
//  ViewController.m
//  NetPhone
//
//  Created by intel intel on 12-4-25.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "CallViewController.h"
#import "GlobalVar.h"
#import "Common.h"
#import "CallRecordViewController.h"
#import "VisitWebViewController.h"
#import "DisPayViewController.h"
#import "DisPayContentViewController.h"
#import "PayViewController.h"
#import "iToast.h"
#import "XMLReader.h"
#import "KeyboardViewController.h"
#import "NSObject+SBJson.h"
#import "SBJsonParser.h"
//#import "ipjsua_app_callback.h"
//
@implementation ViewController
@synthesize tabBarController;

static ViewController *shareViewControllerInstance = nil;

+(ViewController *)sharedInstance
{
    return shareViewControllerInstance;
}

- (BOOL)createEditableCopyOfDatabaseIfNeeded
{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *writableDBPath = [GlobalVar getFilePath:@"main_db.sqlite"];
	NSLog(@"创建数据库===%@",writableDBPath);
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success) return NO;
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"main_db.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success)
    {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
    return YES;
}

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        shareViewControllerInstance = self;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    tabBarController.view.frame = self.view.bounds;
    tabBarController.delegate = self;
    tabBarController.tabBar.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_tabbar"]];
    [self.view addSubview:tabBarController.view];
    //充值
    //PayViewController* chongzhi=[[[PayViewController alloc]init]autorelease];
    DisPayViewController* chongzhi=[[[DisPayViewController alloc]init]autorelease];
    UINavigationController* chongzhiNav=[[[UINavigationController alloc]initWithRootViewController:chongzhi]autorelease];
    //通讯录
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    if ([picker.viewControllers count]>1)
    {
        picker.viewControllers = [NSArray arrayWithObject:[picker.viewControllers objectAtIndex:1]];
    }
    picker.delegate  = self;
    picker.peoplePickerDelegate = self;
    [picker.navigationBar setBarStyle:UIBarStyleBlackOpaque];
    NSMutableArray *newControllers = [NSMutableArray arrayWithArray: [self.tabBarController viewControllers]];
    [newControllers insertObject:picker atIndex:1];
    [picker release];
    [newControllers insertObject:chongzhiNav atIndex:2];
    NSString* vipName=[[NSUserDefaults standardUserDefaults] objectForKey:@"vipName"];
    if ([vipName length]>0)
    {
        VisitWebViewController* visit=[[[VisitWebViewController alloc]init]autorelease];
        UINavigationController* visitNav=[[[UINavigationController alloc]initWithRootViewController:visit]autorelease];
        [newControllers insertObject:visitNav atIndex:2];
    }
    [self.tabBarController setViewControllers: newControllers animated: NO];
    UITabBarItem *tabItem = [[[self.tabBarController tabBar] items] objectAtIndex:1];
    [tabItem setTitle:@"联系人"];
    tabItem.image = [UIImage imageNamed:@"adb"];
    int chongzhiTabItemIndex = 2;
    if ([vipName length]>0)
    {
        UITabBarItem* webTabItem=[[[self.tabBarController tabBar]items]objectAtIndex:2];
        [webTabItem setTitle:vipName];
         webTabItem.image=[UIImage imageNamed:@"web"];
        chongzhiTabItemIndex = 3;
    }
    UITabBarItem* chongzhiTabItem=[[[self.tabBarController tabBar]items]objectAtIndex:chongzhiTabItemIndex];
    [chongzhiTabItem setTitle:@"账户充值"];
    chongzhiTabItem.image=[UIImage imageNamed:@"chongzhi2"];
    //获取直拨信息
    [self getDirectCallInfo];
    //获取接听界面广告
    [self getjietingIm];
    //获取系统公告信息
    [self getSysInfro];
    //软件自动更新检查
    [self updateVersion];
}
//获取直拨信息
-(void)getDirectCallInfo
{
    NSString* prepareMD5=[NSString stringWithFormat:@"%@%@%@",[GlobalVar loginUserKey],SOFT_ID,@"ysyvoip8611"];
    NSString* MD5String=[GlobalVar md5Str:prepareMD5];
    NSMutableDictionary* dic=[NSMutableDictionary dictionary];
    [dic setObject:[GlobalVar loginUserKey] forKey:@"phone"];
    [dic setObject:SOFT_ID forKey:@"agentid"];
    [dic setObject:MD5String forKey:@"md5"];
    NSString* jsonString=[dic  JSONRepresentation];
    ASIHTTPRequest*  request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://zhibo.10086tel.com:8881/sipapi/sipapi.php"]];
    [request setTimeOutSeconds:TIME_OUT_SECONDS];
    [request setDelegate:self];
    [request setPostBody:[NSMutableData dataWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]];
    [request setDidFinishSelector:@selector(askSuccess:)];
    [request setDidFailSelector:@selector(askFail:)];
    [request startAsynchronous];
    
}

#pragma mark获取直拨信息回调
-(void)askSuccess:(ASIHTTPRequest*)request
{
    NSString* sipInfo=[request responseString];
    SBJsonParser* parser=[[SBJsonParser alloc]init];
    NSDictionary* resultDic=[parser objectWithString:sipInfo error:nil];
    //NSLog(@"获取直拨信息回调====%@",resultDic);
    NSString* nsStrDirectDial=@"0";
    NSUserDefaults* userDefaults=[NSUserDefaults standardUserDefaults];
    int code=[[resultDic objectForKey:@"code"] intValue];
    if (code==0)
    {
        //NSLog(@"＝＝＝返回成功＝＝＝＝＝＝");
        //账号
        self.sipphone = [resultDic objectForKey:@"sipphone"];
        //密码
        NSString* sippwd=[resultDic objectForKey:@"sippwd"];
        //ip地址
        NSString* ip=[resultDic objectForKey:@"ip"];
        //端口号
        NSString* port=[resultDic objectForKey:@"port"];
        NSString* domainName=[NSString stringWithFormat:@"%@:%@",ip,port];
        /*
        if ([self.sipphone length]>0 && [sippwd length]>0 && [ip length]>0 && [domainName length]>0 )
        {
            PjsuaAppCallback* callBack=new PjsuaAppCallback();
            pjsuaSetRegAddr([ip UTF8String], [port intValue]);
            pjsuaSetUser([self.sipphone UTF8String], [sippwd UTF8String]);
            //NSString* filePath=[GlobalVar getFilePath:@"direct.txt"];
            //pjsuaSetLogf(5, [filePath UTF8String]);
            //NSLog(@"直拨日志文件:%@",filePath);
            setCallbackObject(callBack);
            pjsuaStart();
        }
         */
        nsStrDirectDial = @"1";
    }else
    {
        NSString* errorMsg=[resultDic objectForKey:@"msg"];
        nsStrDirectDial = @"0";
        NSLog(@"=获取直拨信息回调===%@",errorMsg);
    }
    [userDefaults setObject:nsStrDirectDial forKey:@"DirectDial"];
    [userDefaults synchronize];
}
-(void)askFail:(ASIHTTPRequest*)request
{
    NSLog(@"=====获取直拨信息超时====");
    NSUserDefaults* userDefaults=[NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"0" forKey:@"DirectDial"];
    [userDefaults synchronize];
    
}
//更新软件处理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        NSLog(@"alertView＝%@",updateUrl);
        NSURL *xurl = [[[NSURL alloc]initWithString:updateUrl]autorelease];
        [[UIApplication sharedApplication] openURL:xurl];
    }
    
}

#pragma mark-请求方法
//获取接听界面广告
-(void)getjietingIm
{
    /*
    NSString* CanShu=[NSString stringWithFormat:@"<root><adtype>%@</adtype><cert>%@</cert><productid>%@</productid><platform>iphone</platform><mobile>%@</mobile></root>",@"1",[GlobalVar getTheCertNum],SOFT_ID,[GlobalVar loginUserKey]];
   // NSLog(@"=====请求接听界面广告数据====:%@",CanShu);
    NSLog(@"=====请求接听界面广告数据====");
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:ADVERTISEMENTURL]];
    [request setTimeOutSeconds:30.0f];
    [request setDelegate:self];
    if ([GlobalVar sharedInstance].blnUseProxy==YES)
    {
        [request setProxyPort:ProxyPort];
        [request setProxyHost:[GlobalVar getTheBestIp]];//
    }
    [request setPostBody:[NSMutableData dataWithData:[CanShu dataUsingEncoding:NSUTF8StringEncoding]]];
    [request setDidFinishSelector:@selector(jietingAdSuccess:)];
    [request setDidFailSelector:@selector(jietingAdFail:)];
    [request startAsynchronous];
     */
    NSLog(@"====获取接听界面广告=====");
     HttpForAgent* _httpAgent =[[HttpForAgent alloc]init];
    _httpAgent.delegate=self;
    [_httpAgent requestData:@"1" setUsername:GetAdv];
    
}
//软件自动更新检查
-(void)updateVersion
{
     NSLog(@"======软件自动更新检查=====");
    NSString *CanShu = [NSString stringWithFormat:@"<root><productid>%@</productid><platform>iphone</platform><version>%@</version></root>",SOFT_ID,SOFT_VER];
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:UPDATE_URL]];
    [request setTimeOutSeconds:30.0f];
    [request setDelegate:self];
    if ([GlobalVar sharedInstance].blnUseProxy==YES)
    {
        [request setProxyPort:ProxyPort];
        [request setProxyHost:[GlobalVar getTheBestIp]];//
    }
    [request setPostBody:[NSMutableData dataWithData:[CanShu dataUsingEncoding:NSUTF8StringEncoding]]];
    [request setDidFinishSelector:@selector(updateSuccess:)];
    [request setDidFailSelector:@selector(updateFail:)];
    [request startAsynchronous];
}
//获取系统公告信息
-(void)getSysInfro
{
    NSLog(@"======获取系统公告信息=====");
    NSString* mobilePhone=[[NSUserDefaults standardUserDefaults] objectForKey:@"LOGIN_USER_KEY"];
    NSString* pre_MD5=[NSString stringWithFormat:@"%@%@%@%@",mobilePhone,@"6",SOFT_ID,@"ysw"];
    NSString* MD5Str=[GlobalVar md5Str:pre_MD5];
    //
    ASIFormDataRequest* request;
    if ([GlobalVar sharedInstance].blnUseProxy==YES)
    {
        request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",origin_url_prefix,@"getmsg.php"]]];
        [request setProxyPort:ProxyPort];
        [request setProxyHost:[GlobalVar getTheBestIp]];//
    }else{
        request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",[GlobalVar getTheBestUrl],@"proxy.php"]]];
        [request setPostValue:origin_url_prefix forKey:@"apiurl"];
        [request setPostValue:@"getmsg" forKey:@"act"];
    }
    [request setDelegate:self];
    [request setTimeOutSeconds:30.0f];
    [request setPostValue:mobilePhone forKey:@"mobile"];
    [request setPostValue:SOFT_ID forKey:@"softid"];
    [request setPostValue:@"6" forKey:@"type"];
    [request setPostValue:MD5Str forKey:@"md5"];
    [request setPostValue:MULTIAGENTSWITCH forKey:@"multiAgent"];
    [request setPostValue:NETWORKSTATE forKey:@"apn"];
    [request setPostValue:SOFT_VER forKey:@"version"];
    [request setDidFinishSelector:@selector(getMsgSuccess:)];
    [request setDidFailSelector:@selector(getMsgFail:)];
    [request startAsynchronous];
}

#pragma mark-网络请求返回来数据
//返回接听界面广告数据
-(void)requestAdvSuccess:(NSString*)str
{
    //NSLog(@"==返回接听界面广告数据==");
    //NSLog(@"==返回接听界面广告数据==%@",str);
    NSError *parseError = nil;
    NSDictionary *nsDicData = [XMLReader dictionaryForXMLString:str error:&parseError];
    if (parseError)
    {
        NSLog(@"parseError=====%@",parseError.debugDescription);
        return;
    }
    NSDictionary *xmlDictionary = [[nsDicData valueForKey:@"root"]valueForKey:@"ret"];
    NSString* code = [[xmlDictionary valueForKey:@"code"]valueForKey:@"text"];
    if([code isEqualToString:@"0"])
    {
        int count=[(NSString *)[[xmlDictionary valueForKey:@"adtotal"]valueForKey:@"text"]intValue];;
         NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        [defaults setInteger:count forKey:@"jietingImagecount"];
        for (int i=0; i<count; i++)
        {
            NSString* urlId = [NSString stringWithFormat:@"url%d",i];
            NSString* nsStrUrl=[[xmlDictionary valueForKey:urlId]valueForKey:@"text"];;
            //NSLog(@"url======%@",nsStrUrl);
            NSArray* array=[nsStrUrl componentsSeparatedByString:@"@"];
            NSString* advStr=[array objectAtIndex:0];
            NSString* totalAdStr=[NSString stringWithFormat:@"%@%@",HTTP,advStr];
            //NSLog(@"接听界面广告图片地址====:%@",totalAdStr);
            //
            NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
            [defaults setObject:totalAdStr forKey:[NSString stringWithFormat:@"callStr%d",i]];
        }
        [defaults synchronize];
    }else
    {
         NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        [defaults setInteger:0 forKey:@"jietingImagecount"];
        [defaults synchronize];
    }
}
//获取自动更新返回来的数据
-(void)updateSuccess:(ASIHTTPRequest*)request
{
    NSString* str=[request responseString];
    NSLog(@"==获取自动更新返回来的数据===%@",str);
    //
    if([str rangeOfString:@"<code>0</code>"].location != NSNotFound)
    {
        int xx = [str rangeOfString:@"<url>"].location;
        NSString *value = [str substringFromIndex:xx];
        xx = [value rangeOfString:@"</url>"].location;
        value = [value substringToIndex:xx];
        value = [value stringByReplacingOccurrencesOfString:@"<url>" withString:@""];
        [updateUrl release];
        updateUrl=[value retain];
        [HUD hide:YES];
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDate *startDate = [NSDate date];
        NSDateComponents *dateComps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:startDate];
        int hour=[dateComps hour];
        if ((hour>=8 && hour<10)||(hour>=15 && hour<17)||(hour>=20&&hour<22))
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新"
                                                            message:@"发现新版本，需要更新吗？"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定",@"取消",nil];
            [alert show];
            [alert release];
            
        }
    }
    

}
//获取自动更新地址失败返回来内容
-(void)updateFail:(ASIHTTPRequest*)request
{
    NSLog(@"获取自动更新地址失败返回来内容%@",[request error]);
}
//查询信息回调
-(void)getMsgSuccess:(ASIHTTPRequest*)request
{
    NSString* result=[request responseString];
    if ([result length]>0)
    {
        NSLog(@"查询信息结果====:%@",result);
        NSString* msgCode=[[result componentsSeparatedByString:@"|"]objectAtIndex:0];
        if ([msgCode isEqualToString:@"1"])
        {
            NSString* value=[[result componentsSeparatedByString:@"|"] objectAtIndex:1];
            value=[self NSScanner:value];
            NSCalendar *cal = [NSCalendar currentCalendar];
            NSDate *startDate = [NSDate date];
            NSDateComponents *dateComps = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:startDate];
            int hour=[dateComps hour];
            if (![value isEqualToString:@""])
            {
                if ((hour>=7 && hour<9)||(hour>=13 && hour<14)||(hour>=21&&hour<23))
                {
                    
                    UIAlertView* alertview=[[UIAlertView alloc]initWithTitle:@"提醒" message:value delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    [alertview show];
                    [alertview release];
                    
                }
                
            }
            
        }

    }
}
//查询信息失败
-(void)getMsgFail:(ASIHTTPRequest*)request
{
    iToast* toast=[iToast makeText:ERRORCODE];
    [toast show];
    
}
-(NSString*)NSScanner:(NSString*)str
{
    NSScanner* scanner=[NSScanner scannerWithString:str];
    NSString* text=nil;
    while ([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"\\n" intoString:nil];
        [scanner scanUpToString:@"\n" intoString:&text];
        str=[str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",text] withString:@""];
    }
    return str;
}

-(void)reloadCallRecords:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:UINavigationController.class])
    {
        UIViewController *innervc = ((UINavigationController *)viewController).visibleViewController;
        if ([innervc respondsToSelector:@selector(reloadCallRecords)])
        {
            [innervc performSelector:@selector(reloadCallRecords)];
        }
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [self reloadCallRecords:tabBarController.selectedViewController];
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!isInited)
    {
        isInited = YES;
        [self initNetPhoneData];
    }
}

-(void)initNetPhoneData
{
        BOOL isCreate = [self createEditableCopyOfDatabaseIfNeeded];
        NetPhoneDAO *netPhoneDAO = [NetPhoneDAO sharedInstance];
        if (isCreate)
        {
            HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            HUD.delegate = self;
            HUD.labelText = @"正在为第一次使用准备索引...";
            [HUD showWhileExecuting:@selector(initNetPhoneData:) onTarget:netPhoneDAO withObject:self animated:YES];
        }else{
            [netPhoneDAO initNetPhoneData:nil];
        }
}

-(void)initNetPhoneDataProgress:(NSArray *)array
{
    NSNumber *pro = [array objectAtIndex:0];
    NSNumber *total = [array objectAtIndex:1];
    HUD.detailsLabelText = [NSString stringWithFormat: @"%d/%d",[pro intValue],[total intValue]];
}

- (void)hudWasHidden:(MBProgressHUD *)hud
{
	[HUD removeFromSuperview];
	[HUD release];
	HUD = nil;
}

-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    viewController.navigationItem.rightBarButtonItem = nil;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    return YES;
}


- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    if (property == kABPersonPhoneProperty)
    {
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        self.personPhone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, identifier));
        self.personPhone = [self.personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
        self.personPhone = [self.personPhone stringByReplacingOccurrencesOfString:@"+" withString:@""];
        NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
        self.userName = @"";
        if (firstName)
        {
            if (lastName)
            {
                self.userName = [NSString stringWithFormat:@"%@ %@",lastName,firstName];
            }else{
                self.userName = firstName;
            }
        }else{
            if (lastName)
            {
                self.userName = lastName;
            }
        }
        [self showCallTypeView];
    }
    return NO;
}

-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    if (property == kABPersonPhoneProperty)
    {
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        self.personPhone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, identifier));
        self.personPhone = [self.personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
        self.personPhone = [self.personPhone stringByReplacingOccurrencesOfString:@"+" withString:@""];
        NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
        self.userName = @"";
        if (firstName)
        {
            if (lastName)
            {
                self.userName = [NSString stringWithFormat:@"%@ %@",lastName,firstName];
            }else{
                self.userName = firstName;
            }
        }else{
            if (lastName) {
                self.userName = lastName;
            }
        }
        [self showCallTypeView];
    }
}
-(void)showCallTypeView
{
    NSString* callway = [[NSUserDefaults standardUserDefaults]objectForKey:@"DirectDial"];
    if (callway&& [callway isEqualToString:@"1"])
    {
        
        UIActionSheet* callMethdSheet1=[[UIActionSheet alloc]initWithTitle:@"温馨提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"直拨" otherButtonTitles:@"回拨", nil];
        [callMethdSheet1 showInView:self.view];
    }else{
        ////拨打类型 0.直拨  1.回拨
        [Common callWithNumber:self.personPhone name:self.userName AndTheType:1];
    }
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex<=1)
    {
        if (self.userName && self.userName.length>0)
        {
            [Common callWithNumber:self.personPhone name:self.userName AndTheType:buttonIndex];
        }else
        {
            [Common callWithNumber:self.personPhone name:self.personPhone AndTheType:buttonIndex];
        }
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    [self reloadCallRecords:viewController];
    if (viewController == [[tabBarController viewControllers]objectAtIndex:0])
    {
        UIViewController *innervc = ((UINavigationController *)viewController).visibleViewController;
        if ([innervc respondsToSelector:@selector(showKeyboard)])
        {
            [innervc performSelector:@selector(showKeyboard)];
        }
        
    }
    return YES;
}

-(void)dealloc
{
    [updateUrl release];
    [tabBarController release];
    [super dealloc];
}

@end
